/**
 * 使用hibernate操作数据库
 * @author MIAO
 * Created on 2011-10-11
 * For more information, please visit:ismiao.com
 */
package com.ismiao.example.hbm;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

//SuppressWarnings:抑制编译器产生警告信息的。 
@SuppressWarnings("deprecation")
public class CustomerDAO {
	//数据存储源
	public static SessionFactory sessionFactory;
	static {
		try {
			Configuration config = new Configuration().configure();
			sessionFactory = config.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 将一个customer对象存入database
	 * 
	 * @Customer customer Object
	 */
	public void saveCustomer(Customer c) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(c);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	/*
	 * 查找所有的customer object
	 */
	public void findAll() {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			List<Customer> customers = session.createQuery(
					"from Customer as c order by c.name asc").list();
			Iterator<Customer> it = customers.iterator();
			System.out.println("append:" + customers.size());
			while (it.hasNext()) {
				Customer c = (Customer) it.next();
				System.out.println("ID:" + c.getId());
				System.out.println("NAME:" + c.getName());
				System.out.println("PASSWORD：" + c.getPassword());
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	/*
	 * 修改customer Name
	 * 
	 * @name
	 */
	public void loadUpdate(int customer_id, String name) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Customer c = (Customer) session.load(Customer.class, customer_id);
			c.setName(name);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
